<template>
  <a-modal
    :title="title"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ props: { disabled: disabled } }"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-row style="width: 100%;">
          <a-col :span="24 / 2">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="title"
              label="标题"
            >
              <a-input
                placeholder="请输入标题"
                v-model="model.title"
                :readOnly="disableSubmit"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24 / 2">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="优先级"
            >
              <a-select
                v-model="model.priority"
                placeholder="请选择优先级"
                :disabled="disableSubmit"
                :getPopupContainer="target => target.parentNode"
              >
                <a-select-option value="L">低</a-select-option>
                <a-select-option value="M">中</a-select-option>
                <a-select-option value="H">高</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="width: 100%;">
          <a-col :span="24 / 2">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="startTime"
              label="开始时间:"
            >
              <date
                style="width: 100%"
                :getCalendarContainer="node => node.parentNode"
                v-model="model.startTime"
                :readOnly="disableSubmit"
                placeholder="请选择开始时间"
                showTime
                dateFormat="YYYY-MM-DD HH:mm:ss"
              ></date>
            </a-form-model-item>
          </a-col>
          <a-col :span="24 / 2">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="endTime"
              label="结束时间"
              class="endTime"
            >
              <date
                style="width: 100%"
                :getCalendarContainer="node => node.parentNode"
                v-model="model.endTime"
                :readOnly="disableSubmit"
                placeholder="请选择结束时间"
                showTime
                dateFormat="YYYY-MM-DD HH:mm:ss"
              ></date>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="width: 100%;">
          <a-col :span="24 / 2">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="msgType"
              label="通告类型"
            >
              <a-select
                v-model="model.msgType"
                placeholder="请选择通告类型"
                :disabled="disableSubmit"
                @change="chooseMsgType"
                :getPopupContainer="target => target.parentNode"
              >
                <a-select-option value="USER">指定用户</a-select-option>
                <a-select-option value="ALL">全体用户</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24 / 2">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="指定用户"
              v-if="userType"
            >
              <a-select
                mode="multiple"
                placeholder="请选择用户"
                :disabled="disableSubmit"
                :labelInValue="true"
                v-model="selectedUser"
                @dropdownVisibleChange="selectUserIds"
                @change="handleChange"
              >
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="width: 100%;">
          <a-col :span="24">
            <a-form-model-item
              :labelCol="labelColX1"
              :wrapperCol="wrapperColX1"
              label="内容"
              class="j-field-content"
            >
              <a-textarea
                rows="7"
                placeholder="请输入内容"
                :disabled="disableSubmit"
                v-model="model.msgContent"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
    <select-user-list-modal
      ref="UserListModal"
      @choseUser="choseUser"
    ></select-user-list-modal>
  </a-modal>
</template>

<script>
import Date from "../../../components/datetime/Date";
import SelectUserListModal from "../user/SelectUserListModal";
import moment from "moment";

export default {
  components: { Date, SelectUserListModal },
  name: "NoticeAddModal",
  data() {
    return {
      title: "操作",
      visible: false,
      disableSubmit: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      labelColX1: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperColX1: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      confirmLoading: false,
      validatorRules: {
        title: [{ required: true, message: "请输入标题!" }],
        msgType: [{ required: true, message: "请选择通告对象类型!" }],
        endTime: [
          { required: true, message: "请选择结束时间!" },
          { validator: this.endTimeValidate }
        ],
        startTime: [
          { required: true, message: "请选择开始时间!" },
          { validator: this.startTimeValidate }
        ]
      },
      url: {
        queryByIds: "/api/user/queryByIds",
        add: "/api/notice/add",
        update: "/api/notice/update"
      },
      userType: false,
      userIds: [],
      selectedUser: [],
      disabled: false,
      msgContent: "",
      userList: []
    };
  },
  created() {},
  methods: {
    add() {
      this.edit({});
    },
    edit(record) {
      this.model = {};
      this.disable = false;
      this.visible = true;
      this.getUser(record);
    },
    getUser(record) {
      this.model = Object.assign({}, record);
      // 指定用户
      if (record && record.msgType === "USER") {
        this.userType = true;
        this.userIds = record.userIds;
        this.$get(this.url.queryByIds, { userIds: this.userIds }).then(r => {
          if (r.data.success) {
            const data = r.data.data;
            const userList = [];
            for (let i = 0; i < data.length; i++) {
              const user = {};
              user.label = data[i].userName;
              user.key = data[i].userId;
              userList.push(user);
            }
            this.selectedUser = userList;
            this.$refs.UserListModal.edit(data, this.userIds);
          }
        });
      }
    },
    close() {
      this.$emit("close");
      this.selectedUser = [];
      this.visible = false;
      this.$refs.form.resetFields();
    },
    handleOk() {
      const that = this;
      //当设置指定用户类型，但用户为空时，后台报错
      if (this.userType && !(this.userIds != null && this.userIds.length > 0)) {
        this.$message.warning("指定用户不能为空！");
        return;
      }
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          if (this.userType) {
            this.model.userIds = this.userIds;
          }
          if (!this.model.id) {
            this.$post(this.url.add, this.model)
              .then(r => {
                if (r.data.success) {
                  that.$message.success("新增成功");
                  that.$emit("ok");
                  that.resetUser();
                } else {
                  that.$message.warning("新增失败");
                }
              })
              .finally(() => {
                that.confirmLoading = false;
                that.close();
              });
          } else {
            this.$put(this.url.update, this.model)
              .then(r => {
                if (r.data.success) {
                  that.$message.success("更新成功");
                  that.$emit("ok");
                  that.resetUser();
                } else {
                  that.$message.warning("更新失败");
                }
              })
              .finally(() => {
                that.confirmLoading = false;
                that.close();
              });
          }
        } else {
          return false;
        }
      });
    },
    handleCancel() {
      this.visible = false;
      this.$emit("close");
      this.$refs.form.resetFields();
      this.resetUser();
    },
    resetUser() {
      this.userType = false;
      this.userIds = [];
      this.selectedUser = [];
      this.disabled = false;
      this.$refs.UserListModal.edit(null, null);
    },
    selectUserIds() {
      this.$refs.UserListModal.add(this.selectedUser, this.userIds);
    },
    chooseMsgType(value) {
      if ("USER" === value) {
        this.userType = true;
      } else {
        this.userType = false;
        this.selectedUser = [];
        this.userIds = [];
      }
    },
    // 子modal回调
    choseUser: function(userList) {
      this.selectedUser = [];
      this.userIds = [];
      for (let i = 0; i < userList.length; i++) {
        const user = {};
        user.label = userList[i].userName;
        user.key = userList[i].userId;
        this.selectedUser.push(user);
        this.userIds += userList[i].userId + ",";
      }
    },
    startTimeValidate(rule, value, callback) {
      let endTime = this.model.endTime;
      if (!value || !endTime) {
        callback();
      } else if (moment(value).isBefore(endTime)) {
        callback();
      } else {
        callback("开始时间需小于结束时间");
      }
    },
    endTimeValidate(rule, value, callback) {
      let startTime = this.model.startTime;
      if (!value || !startTime) {
        callback();
      } else if (moment(startTime).isBefore(value)) {
        callback();
      } else {
        callback("结束时间需大于开始时间");
      }
    },
    handleChange(userList) {
      const users = [];
      if (userList) {
        this.userIds = [];
        for (let i = 0; i < userList.length; i++) {
          const user = {};
          user.userId = userList[i].key;
          user.userName = userList[i].label;
          this.userIds += userList[i].key + ",";
          users.push(user);
        }
      }
      this.$refs.UserListModal.edit(users, this.userIds);
    }
  }
};
</script>

<style scoped></style>
